
'use strict';

const Service = require('egg').Service;
const utility = require('utility');

class LoginService extends Service {
    async validateAccount() {
        const { ctx } = this;
        ctx.logger.error('成功请求到Service', account.username, account);
        const info = await ctx.userModel.OperatorUser.findOne({ where: { mobile: account.username } });
        ctx.logger.error(info.salt, '查询信息数据');
        if (!info) {
            return JSON.stringify({ code: '500', data: {}, message: '登录账号错误' });
        }
        ctx.logger.error('查询信息成功');
        // 加密密码并验证是否正确
        // this.app.config.jwt.secret = info.salt;
        const md5Value = utility.md5(`${account.password}{${info.salt}}`);
        ctx.logger.error('加密密码', md5Value);

        if (info.password !== md5Value) {
            return JSON.stringify({ code: '500', data: {}, message: '登录密码错误' });
        }
        ctx.logger.error('加密成功，验证密码成功');
        // 生成并保存token
        const token = this.createToken({ id: info.id, mobile: info.mobile });
        ctx.logger.error('保存token成功');
        const user = JSON.stringify({
            code: '200',
            data: {
                business_id: '1',
                mobile: info.mobile,
                roles: [info.roles],
                uid: info.uid,
                username: info.username,
                token: token,
            },
            message: 'success',
        });
        ctx.logger.error('转化为字符串成功');
        return user;
    }

    /**
       * 生成 Token
       * @param {Object} data
       */
    createToken(data) {
        return this.app.jwt.sign(data, this.app.config.jwt.secret, {
            expiresIn: '12h',
        });
    }

    /**
     * 验证token的合法性
     * @param {String} token
     */
    verifyToken(token) {
        return new Promise((resolve) => {
            this.app.jwt.verify(token, this.app.config.jwt.secret, (err, decoded) => {
                let result = { verify: false, message: '' };
                if (err && !token) {
                    /*
                      err = {
                        name: 'TokenExpiredError',
                        message: 'jwt expired',
                        expiredAt: 1408621000
                      }
                    */
                    result.verify = false;
                    result.message = err.message;
                } else {
                    result.verify = true;
                    result.message = decoded;
                }
                resolve(result);
            });
        });
    }
}

module.exports = LoginService;
